import { useState, useEffect, useCallback } from 'react'
import { workoutService } from '@/services/workoutService'

export function useWorkoutManagement() {
  const [workouts, setWorkouts] = useState([])
  const [showForm, setShowForm] = useState(false)
  const [editingWorkout, setEditingWorkout] = useState(null)
  const [currentWorkout, setCurrentWorkout] = useState(null)

  const loadWorkouts = useCallback(() => {
    setWorkouts(workoutService.getPlans())
  }, [])

  const checkWorkouts = useCallback(() => {
    const now = new Date()
    const currentTime = `${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}`
    const workout = workouts.find(w =>
      w.time === currentTime && w.days.includes(now.getDay())
    )
    if (workout) {
      setCurrentWorkout(workout)
    }
  }, [workouts])

  const handleSubmit = useCallback(async (data) => {
    try {
      const updatedWorkout = {
        ...data,
        id: editingWorkout?.id || undefined
      }
      await workoutService.savePlan(updatedWorkout)
      loadWorkouts()
      setShowForm(false)
      setEditingWorkout(null)
    } catch (error) {
      console.error('保存失败:', error)
      throw error
    }
  }, [editingWorkout, loadWorkouts])

  const handleEdit = useCallback((workout) => {
    setEditingWorkout({
      ...workout,
      days: workout.days || [],
      exercises: workout.exercises || []
    })
    setShowForm(true)
  }, [])

  const handleDelete = useCallback(async (id) => {
    if (window.confirm('确定要删除这个训练计划吗？')) {
      try {
        await workoutService.deletePlan(id)
        loadWorkouts()
      } catch (error) {
        console.error('删除失败:', error)
        throw error
      }
    }
  }, [loadWorkouts])

  useEffect(() => {
    loadWorkouts()
    checkWorkouts()
    const interval = setInterval(checkWorkouts, 60000)
    return () => clearInterval(interval)
  }, [loadWorkouts, checkWorkouts])

  return {
    workouts,
    showForm,
    editingWorkout,
    currentWorkout,
    setShowForm,
    setEditingWorkout,
    handleSubmit,
    handleEdit,
    handleDelete,
    loadWorkouts,
    stats: {
      totalWorkouts: workouts.length,
      weeklyWorkouts: workouts.reduce((acc, w) => acc + w.days.length, 0),
      nextWorkout: workouts.length > 0 ? workouts[0].time : '暂无安排',
      streak: 5
    }
  }
}